"use client"

import { useState, useEffect } from "react"
import { useParams, useNavigate } from "react-router-dom"
import {
  Card,
  Row,
  Col,
  Button,
  Space,
  Tabs,
  Empty,
  Spin,
  Statistic,
  Typography,
  Divider,
  Tag,
  Alert,
  Table,
  Tooltip,
  Modal,
  Input,
  message,
} from "antd"
import {
  PlusOutlined,
  TeamOutlined,
  ProjectOutlined,
  DatabaseOutlined,
  GlobalOutlined,
  ApiOutlined,
  CloudOutlined,
  AppstoreOutlined,
  ArrowLeftOutlined,
  EditOutlined,
  DeleteOutlined,
  CopyOutlined,
  ExportOutlined,
} from "@ant-design/icons"
import { useHosts } from "../contexts/HostsContext"
import HostCard from "../components/HostCard"
import AddEditHostModal from "../components/AddEditHostModal"
import type { Host, Project } from "../types"
import dayjs from "dayjs"

const { TabPane } = Tabs
const { Title, Paragraph, Text } = Typography
const { TextArea } = Input

const ProjectView = () => {
  const { projectId } = useParams<{ projectId: string }>()
  const navigate = useNavigate()
  const { hosts, departments, projects, loading, deleteHost } = useHosts()

  const [isModalVisible, setIsModalVisible] = useState(false)
  const [isExportModalVisible, setIsExportModalVisible] = useState(false)
  const [editingHost, setEditingHost] = useState<Host | null>(null)
  const [project, setProject] = useState<Project | null>(null)
  const [projectHosts, setProjectHosts] = useState<Host[]>([])
  const [exportContent, setExportContent] = useState("")
  const [viewMode, setViewMode] = useState<"card" | "table">("card")

  useEffect(() => {
    if (projectId && projects.length > 0) {
      const proj = projects.find((p) => p.id === projectId) || null
      setProject(proj)

      if (proj) {
        // Get hosts for this project
        const projHosts = hosts.filter((h) => h.projectId === projectId)
        setProjectHosts(projHosts)
      }
    }
  }, [projectId, projects, hosts])

  const handleAddHost = () => {
    setEditingHost(null)
    setIsModalVisible(true)
  }

  const handleEditHost = (host: Host) => {
    setEditingHost(host)
    setIsModalVisible(true)
  }

  const handleDeleteHost = (id: string) => {
    deleteHost(id)
  }

  const handleModalClose = () => {
    setIsModalVisible(false)
    setEditingHost(null)
  }

  const handleBack = () => {
    navigate(-1)
  }

  const handleExport = () => {
    // Generate hosts file content
    const content = projectHosts
      .map((host) => {
        if (host.isComment) {
          return host.commentText
        }
        return `${host.ip} ${host.domain} # ${host.title}`
      })
      .join("\n")

    setExportContent(content)
    setIsExportModalVisible(true)
  }

  const handleCopyExport = () => {
    navigator.clipboard.writeText(exportContent)
    message.success("已复制到剪贴板")
  }

  const handleDownloadExport = () => {
    const blob = new Blob([exportContent], { type: "text/plain" })
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement("a")
    a.href = url
    a.download = `${project?.name || "hosts"}.hosts`
    document.body.appendChild(a)
    a.click()
    window.URL.revokeObjectURL(url)
    document.body.removeChild(a)
    message.success("下载成功")
  }

  // Count hosts by type
  const hostsByType = projectHosts.reduce(
    (acc, host) => {
      acc[host.type] = (acc[host.type] || 0) + 1
      return acc
    },
    {} as Record<string, number>,
  )

  if (loading) {
    return (
      <div style={{ textAlign: "center", padding: "40px 0" }}>
        <Spin size="large" />
      </div>
    )
  }

  if (!project) {
    return (
      <Alert
        message="项目不存在"
        description="您访问的项目不存在或已被删除"
        type="error"
        showIcon
        action={
          <Button type="primary" onClick={handleBack}>
            返回
          </Button>
        }
      />
    )
  }

  const department = departments.find((d) => d.id === project.departmentId)

  const columns = [
    {
      title: "名称",
      dataIndex: "title",
      key: "title",
      sorter: (a: Host, b: Host) => a.title.localeCompare(b.title),
    },
    {
      title: "IP",
      dataIndex: "ip",
      key: "ip",
      copyable: true,
    },
    {
      title: "域名",
      dataIndex: "domain",
      key: "domain",
      copyable: true,
    },
    {
      title: "类型",
      dataIndex: "type",
      key: "type",
      render: (type: string) => {
        const typeIcons = {
          frontend: <GlobalOutlined />,
          backend: <ApiOutlined />,
          database: <DatabaseOutlined />,
          cache: <CloudOutlined />,
          other: <AppstoreOutlined />,
        }

        return (
          <Tag icon={typeIcons[type as keyof typeof typeIcons]} className={`host-type-${type}`}>
            {type === "frontend"
              ? "前端"
              : type === "backend"
                ? "后端"
                : type === "database"
                  ? "数据库"
                  : type === "cache"
                    ? "缓存"
                    : "其他"}
          </Tag>
        )
      },
      filters: [
        { text: "前端", value: "frontend" },
        { text: "后端", value: "backend" },
        { text: "数据库", value: "database" },
        { text: "缓存", value: "cache" },
        { text: "其他", value: "other" },
      ],
      onFilter: (value: string, record: Host) => record.type === value,
    },
    {
      title: "更新时间",
      dataIndex: "lastUpdated",
      key: "lastUpdated",
      render: (date: string) => dayjs(date).format("YYYY-MM-DD HH:mm"),
      sorter: (a: Host, b: Host) => dayjs(a.lastUpdated).unix() - dayjs(b.lastUpdated).unix(),
    },
    {
      title: "操作",
      key: "action",
      render: (_: any, record: Host) => (
        <Space size="small">
          <Tooltip title="编辑">
            <Button type="text" icon={<EditOutlined />} onClick={() => handleEditHost(record)} />
          </Tooltip>
          <Tooltip title="复制">
            <Button
              type="text"
              icon={<CopyOutlined />}
              onClick={() => {
                navigator.clipboard.writeText(`${record.ip} ${record.domain}`)
              }}
            />
          </Tooltip>
          <Tooltip title="删除">
            <Button type="text" danger icon={<DeleteOutlined />} onClick={() => handleDeleteHost(record.id)} />
          </Tooltip>
        </Space>
      ),
    },
  ]

  return (
    <div>
      <Button icon={<ArrowLeftOutlined />} onClick={handleBack} style={{ marginBottom: 16 }}>
        返回
      </Button>

      <Card>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16 }}>
          <div>
            <Title level={3}>
              <ProjectOutlined /> {project.name}
            </Title>
            <Space>
              {department && (
                <Tag icon={<TeamOutlined />} className={`department-tag-${department.code}`}>
                  {department.name}
                </Tag>
              )}
              <Tag color="blue">{project.environment}</Tag>
            </Space>
            <Paragraph style={{ marginTop: 8 }}>{project.description || "暂无描述"}</Paragraph>
          </div>
          <Space>
            <Button icon={<ExportOutlined />} onClick={handleExport}>
              导出 Hosts
            </Button>
            <Button type="primary" icon={<PlusOutlined />} onClick={handleAddHost}>
              添加主机
            </Button>
          </Space>
        </div>

        <Divider />

        <Row gutter={[16, 16]} className="dashboard-stats">
          <Col xs={24} sm={12} md={6}>
            <Card className="stat-card">
              <Statistic
                title="总主机数"
                value={projectHosts.length}
                prefix={<DatabaseOutlined />}
                valueStyle={{ color: "#1890ff" }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Card className="stat-card">
              <Statistic
                title="前端主机"
                value={hostsByType.frontend || 0}
                prefix={<GlobalOutlined />}
                valueStyle={{ color: "#1890ff" }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Card className="stat-card">
              <Statistic
                title="后端主机"
                value={hostsByType.backend || 0}
                prefix={<ApiOutlined />}
                valueStyle={{ color: "#722ed1" }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Card className="stat-card">
              <Statistic
                title="数据库主机"
                value={hostsByType.database || 0}
                prefix={<DatabaseOutlined />}
                valueStyle={{ color: "#52c41a" }}
              />
            </Card>
          </Col>
        </Row>

        <Divider orientation="left">主机列表</Divider>

        <div style={{ marginBottom: 16, textAlign: "right" }}>
          <Space>
            <Button type={viewMode === "card" ? "primary" : "default"} onClick={() => setViewMode("card")}>
              卡片视图
            </Button>
            <Button type={viewMode === "table" ? "primary" : "default"} onClick={() => setViewMode("table")}>
              表格视图
            </Button>
          </Space>
        </div>

        <Tabs defaultActiveKey="all">
          <TabPane tab="全部" key="all">
            {projectHosts.length === 0 ? (
              <Empty description="暂无主机" />
            ) : viewMode === "card" ? (
              <Row gutter={[16, 16]}>
                {projectHosts.map((host) => (
                  <Col xs={24} sm={12} md={8} lg={6} key={host.id}>
                    <HostCard
                      host={host}
                      departments={departments}
                      projects={projects}
                      onEdit={handleEditHost}
                      onDelete={handleDeleteHost}
                    />
                  </Col>
                ))}
              </Row>
            ) : (
              <Table
                columns={columns}
                dataSource={projectHosts}
                rowKey="id"
                className="hosts-table"
                pagination={{
                  pageSize: 10,
                  showSizeChanger: true,
                  showTotal: (total) => `共 ${total} 条记录`,
                }}
              />
            )}
          </TabPane>
          <TabPane tab="前端" key="frontend">
            {projectHosts.filter((h) => h.type === "frontend").length === 0 ? (
              <Empty description="暂无前端主机" />
            ) : viewMode === "card" ? (
              <Row gutter={[16, 16]}>
                {projectHosts
                  .filter((host) => host.type === "frontend")
                  .map((host) => (
                    <Col xs={24} sm={12} md={8} lg={6} key={host.id}>
                      <HostCard
                        host={host}
                        departments={departments}
                        projects={projects}
                        onEdit={handleEditHost}
                        onDelete={handleDeleteHost}
                      />
                    </Col>
                  ))}
              </Row>
            ) : (
              <Table
                columns={columns}
                dataSource={projectHosts.filter((h) => h.type === "frontend")}
                rowKey="id"
                className="hosts-table"
                pagination={{
                  pageSize: 10,
                  showSizeChanger: true,
                  showTotal: (total) => `共 ${total} 条记录`,
                }}
              />
            )}
          </TabPane>
          <TabPane tab="后端" key="backend">
            {projectHosts.filter((h) => h.type === "backend").length === 0 ? (
              <Empty description="暂无后端主机" />
            ) : viewMode === "card" ? (
              <Row gutter={[16, 16]}>
                {projectHosts
                  .filter((host) => host.type === "backend")
                  .map((host) => (
                    <Col xs={24} sm={12} md={8} lg={6} key={host.id}>
                      <HostCard
                        host={host}
                        departments={departments}
                        projects={projects}
                        onEdit={handleEditHost}
                        onDelete={handleDeleteHost}
                      />
                    </Col>
                  ))}
              </Row>
            ) : (
              <Table
                columns={columns}
                dataSource={projectHosts.filter((h) => h.type === "backend")}
                rowKey="id"
                className="hosts-table"
                pagination={{
                  pageSize: 10,
                  showSizeChanger: true,
                  showTotal: (total) => `共 ${total} 条记录`,
                }}
              />
            )}
          </TabPane>
        </Tabs>
      </Card>

      <AddEditHostModal
        visible={isModalVisible}
        host={editingHost}
        departments={departments}
        projects={projects}
        defaultProjectId={projectId}
        onClose={handleModalClose}
      />

      <Modal
        title="导出 Hosts 文件"
        open={isExportModalVisible}
        onCancel={() => setIsExportModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setIsExportModalVisible(false)}>
            关闭
          </Button>,
          <Button key="copy" icon={<CopyOutlined />} onClick={handleCopyExport}>
            复制内容
          </Button>,
          <Button key="download" type="primary" icon={<ExportOutlined />} onClick={handleDownloadExport}>
            下载文件
          </Button>,
        ]}
        width={700}
      >
        <div style={{ marginBottom: 16 }}>
          <Text type="secondary">以下是生成的 hosts 文件内容，您可以复制或下载：</Text>
        </div>
        <TextArea value={exportContent} rows={15} readOnly style={{ fontFamily: "monospace" }} />
      </Modal>
    </div>
  )
}

export default ProjectView
